package cn.sunchis.demo.redisson;

import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.RedissonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Redisson自动配置
 * @Author 许亮
 * @Create 2018-9-4 21:21:33
 */
@Configuration
@EnableConfigurationProperties(RedissonConfig.class)
public class RedissonAutoConfiguration {
	@Autowired
	private Environment environment;
	@Autowired
	private RestTemplate restTemplate;
	
	@Bean
	public RedissonClient redissonClient() throws IOException {
		String profile = "";
		String[] profiles = environment.getActiveProfiles();
		
		if (profiles.length > 0) {
			profile = profiles[0];
		}
		
		String redissonUrl = String.format("http://spring-cloud-config-server/redisson-%s.yml", profile);
		ResponseEntity<String> responseEntity = restTemplate.getForEntity(redissonUrl, String.class);
		System.err.println(responseEntity.getBody());
		
		Config config = Config.fromYAML(new ClassPathResource("redisson" + profile + ".yml").getInputStream());
		RedissonClient redissonClient = Redisson.create(config);
		return redissonClient;
	}
}
